package ita.class1.group2.supermarket.common.captain.manager;

import ita.class1.group2.supermarket.common.annotation.Component;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ContextManager {

    private ServletContext servletContext = null;
    private ConcurrentHashMap<String, HttpSession> sessionConcurrentHashMap = null;


    public void initialize(ServletContext servletContext) {
        this.servletContext = servletContext;
        this.sessionConcurrentHashMap = new ConcurrentHashMap<String, HttpSession>();
    }

    public ServletContext getServletContext() {
        return this.servletContext;
    }

    public void addSession(HttpSession session) {
        String currentThreadId = String.valueOf(Thread.currentThread().getId());
        if (sessionConcurrentHashMap.containsKey(currentThreadId)) {
            System.err.println("can not add temp session");
            return;
        }
        this.sessionConcurrentHashMap.put(currentThreadId, session);
    }

    public HttpSession getSession() {
        return this.sessionConcurrentHashMap.get(String.valueOf(Thread.currentThread().getId()));
    }

    public void removeSession() {
        this.sessionConcurrentHashMap.remove(String.valueOf(Thread.currentThread().getId()));
    }

}
